// 购物车模块
import { insertCart, findCartList, deleteCart, updateCart, checkAllCart } from '@/api/cart'

const cart = {
  namespaced: true,
  state: () => ({
    list: [] // 购物车列表
  }),
  mutations: {
    setList (state, newList) {
      state.list = newList
    }
  },
  actions: {
    // 加入购物车
    async asyncInsertCart (ctx, { skuId, count }) {
      // 添加购物车
      await insertCart({ skuId, count })
      // 添加完成后获取最新购物车列表
      const res = await findCartList()
      ctx.commit('setList', res.result)
    },

    // 删除 skuId组成的数组
    async asyncDelCart (ctx, ids) {
      await deleteCart(ids)
      const res = await findCartList()
      ctx.commit('setList', res.result)
    },

    // 更新购物车
    async asyncUpdateList (ctx) {
      const res = await findCartList()
      ctx.commit('setList', res.result)
    },

    // 单选
    async asyncCheck (ctx, good) {
      await updateCart(good)
      const res = await findCartList()
      ctx.commit('setList', res.result)
    },

    // 全选
    async asyncAllCheck (ctx, selected) {
      // 修改全选的状态
      const ids = ctx.state.list.map(item => item.skuId)
      await checkAllCart({ selected, ids })
      // 重新调用后台数据
      const res = await findCartList()
      ctx.commit('setList', res.result)
    },

    // 修改数量
    async asyncChangeNum (ctx, good) {
      await updateCart(good)
      const res = await findCartList()
      ctx.commit('setList', res.result)
    }
  },
  getters: {
    // 总数
    allCount (state) {
      return state.list.reduce((a, c) => a + c.count, 0)
    },

    // 总钱数
    allPrice (state) {
      return state.list.reduce((a, c) => a + c.price * c.count, 0)
    },

    // 选中的总数
    selectedAllCount (state) {
      return state.list.filter(item => item.selected).reduce((a, c) => a + c.count, 0)
    },

    // 选中的总钱数
    selectedAllPrice (state) {
      return state.list.filter(item => item.selected).reduce((a, c) => a + c.price * c.count, 0)
    },

    // 全选的状态
    AllSelected (state) {
      return state.list.every(item => item.selected)
    }
  }
}

export default cart
